package com.financial.sys.controller.register;

import com.financial.common.constants.ResultCodeEnum;
import com.financial.common.vo.Result;
import com.financial.model.pojo.TUserAccount;
import com.financial.sys.service.register.registerAndLoginService;
import com.financial.sys.util.JwtUtil;
import com.financial.sys.util.SHAUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户登录")
@RestController
@RequestMapping("/user")
public class RegisterAndLoginController {

    @Autowired
    private registerAndLoginService loginService;


    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public Result login(@RequestParam(name = "username", required = false) String username,
                        @RequestParam(name = "password", required = false) String password) {
        System.out.println(username+password+"---");
        boolean s=loginService.checkUsername(username);
        if(s==true) {
            return Result.error().message("用户名不存在,请注册!");
        }
        String pwd = SHAUtils.encodeData(password);
        TUserAccount user =
                loginService.findUsernameAndPassword(username,pwd);
        if (user == null) {
            return Result.error().message("登录失败,用户名密码错误!");
        }
        String token = JwtUtil.getToken(username);
        return Result.ok().data(user);
    }

    @PostMapping("register")
    @ApiOperation(value = "用户注册")
    public Result UserAdd(
            @RequestParam(name = "username", required = false) String username,
            @RequestParam(name = "password", required = false) String password) {
        String pwd = SHAUtils.encodeData(password);
        int i=loginService.UserAdd(username,pwd);
        if (i>0) {
            return Result.ok().data(i);
        }
        return Result.error().data(ResultCodeEnum.REGISTER_FAILURE);
    }

    //判断用户名是否存在
    @PostMapping("checkUsername")
    public Boolean checkUsername(@RequestParam(name = "username", required = false) String username){
        return loginService.checkUsername(username);
    }



}
